package com.airnewslinkosky.ticket.ui.personcenter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.airnewslinkosky.ticket.R;
import com.airnewslinkosky.ticket.model.Passenger;
import com.airnewslinkosky.ticket.pay.util.BaseHelper;
import com.airnewslinkosky.ticket.sql.FavoriteInfoDB;
import com.airnewslinkosky.ticket.ui.BaseActivity;
import com.airnewslinkosky.ticket.ui.PersonCenter;
import com.airnewslinkosky.ticket.ui.flight.MileagerInfoAdd;
import com.airnewslinkosky.ticket.ui.flight.MileagerInfoEdit;
import com.airnewslinkosky.ticket.ui.flight.MileagerInfoList;
import com.airnewslinkosky.ticket.util.CheckCetiType;
import com.airnewslinkosky.ticket.util.FlyUtil;
import com.airnewslinkosky.ticket.util.Utils;
import com.mobclick.android.MobclickAgent;

public class PersonPassengerAdd extends BaseActivity implements
		AdapterView.OnItemClickListener {

	public  final int DIALOG_IDTYPE_LIST = 10;
	public  final int DATE_DIALOG_ID = 9;
	public  final int DELETE_MILEAGER_DIALOG = 8;
	
	public static Passenger passenger;//本页的登机人信息
	
	private Button backBut;
	public SimpleAdapter sa;
	public ListView lv;
	public Button mBtnBack,mBtnNext,passengerSaveBut,mileagerInfoAddBut,mileagerInfoGetBut;
	public List<Map<String, String>> data = new ArrayList<Map<String, String>>();
	
	public static List<Map<String, String>> mileagerInfoList = new ArrayList<Map<String, String>>();

	private ProgressDialog progressDialog = null;
	//证件类型,生日
	private TextView idType,birthday;
	private LinearLayout idTypeLay,birthdayLay;
	
	private static int position;
	private int mYear;
    private int mMonth;
    private int mDay;
    private String sex = "0";
    
    //登机人,证件号码,手机号码
    private EditText cnName,idNumber,mobile,email;
    private TextView no_mileagerInfo_alert;
    private Toast toast;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.fly_passenger_info);
		// 删除窗口背景
        getWindow().setBackgroundDrawable(null);
		activityList.add(this);
		
		data = FavoriteInfoDB.selectPsgInfoList(PersonPassengerAdd.this);
		
		idTypeLay = (LinearLayout)findViewById(R.id.idTypeLay);
		idType =  (TextView)findViewById(R.id.idType);
		
		//初始时，出生日期隐藏
		birthdayLay = (LinearLayout)findViewById(R.id.birthdayLay);
		birthday =  (TextView)findViewById(R.id.birthday);
		birthdayLay.setVisibility(View.GONE);
		
		backBut = (Button)findViewById(R.id.backBut);
		
		//得到当前日期
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        cnName = (EditText)findViewById(R.id.cnName);
        idNumber = (EditText)findViewById(R.id.idNumber);
        mobile = (EditText)findViewById(R.id.mobile);
        email = (EditText)findViewById(R.id.email);
        
        passengerSaveBut = (Button)findViewById(R.id.passengerSaveBut);
        mileagerInfoAddBut = (Button)findViewById(R.id.button_add_mileagerInfo);
        mileagerInfoGetBut = (Button)findViewById(R.id.button_get_mileagerInfo);
        
        if(passenger!=null) {
        	cnName.setText(passenger.getPassengerName());
        	idNumber.setText(passenger.getPassengerIDNo());
        	mobile.setText(passenger.getPassengerMobile());
        	birthday.setText(passenger.getPassagerBirthday());
        	email.setText(passenger.getEmail());
        	idType.setText(passenger.getPassengerIDType());
        }
		//常旅卡
		sa = new SimpleAdapter(
				this,
				mileagerInfoList,
				R.layout.flight_mileager_item,
				new String[] { "mileagerCardAirline", "mileagerCardNumber"},
				new int[] { R.id.mileagerCardAirline, R.id.mileagerCardNumber});
		lv = (ListView) findViewById(R.id.mileagerInfo_list);
		lv.setAdapter(sa);
		lv.setOnItemClickListener(this);
		
		no_mileagerInfo_alert = (TextView)findViewById(R.id.no_mileagerInfo_alert);
		if(mileagerInfoList.size() != 0) {
			no_mileagerInfo_alert.setVisibility(View.GONE);
			Utils.setListViewHeightBasedOnChildren(lv);//更新list高度
		} else {
			no_mileagerInfo_alert.setVisibility(View.VISIBLE);
			no_mileagerInfo_alert.setText("暂未添加常旅卡信息 ！");
		}
		
		backBut.setOnClickListener(b_ocl);
		idTypeLay.setOnClickListener(b_ocl);
		birthdayLay.setOnClickListener(b_ocl);
		
		mileagerInfoAddBut.setOnClickListener(b_ocl);
		passengerSaveBut.setOnClickListener(b_ocl);
		mileagerInfoGetBut.setOnClickListener(b_ocl);
		
	    
	}
	
	private Passenger copyPassenger() {
		Passenger passenger = new Passenger();
		passenger.setPassengerName(String.valueOf(cnName.getText()));
		passenger.setPassengerMobile(String.valueOf(mobile.getText()));
		passenger.setPassengerIDType(String.valueOf(idType.getText()));
		passenger.setPassengerIDNo(String.valueOf(idNumber.getText()));
		passenger.setPassagerBirthday(String.valueOf(mobile.getText()));
		passenger.setEmail(String.valueOf(email.getText()));
		return passenger;
	}
	
	OnClickListener b_ocl= new OnClickListener() { 
    	public void onClick(View v) { 
    		switch (v.getId()) {
	    		case R.id.backBut:
	    			Intent intent3 = new Intent();
	    			intent3.setClass(PersonPassengerAdd.this, PersonCenter.class);
	    			startActivity(intent3);
	    			break;
	    		case R.id.idTypeLay:
	    			showDialog(DIALOG_IDTYPE_LIST);
	    			break;
	    		case R.id.birthdayLay:
	    			showDialog(DATE_DIALOG_ID);
	    			break;
	    		case R.id.button_add_mileagerInfo:
	    			Intent intentM = new Intent();
	    			intentM.setClass(PersonPassengerAdd.this, MileagerInfoAdd.class);
	    			MileagerInfoAdd.passenger = copyPassenger();
	    			MileagerInfoAdd.fromAction = "ADD";
					startActivity(intentM);
	    			break;	
	    		case R.id.button_get_mileagerInfo:
	    			System.out.println("enter into MileagerInfoList*************************");
	    			Intent intentGet = new Intent();
					intentGet.setClass(PersonPassengerAdd.this, MileagerInfoList.class);
					MileagerInfoList.passenger = copyPassenger();
					MileagerInfoList.fromAction = "ADD";
					startActivity(intentGet);
	    			break;
	    		case R.id.passengerSaveBut:
	    			String birthdayValue = "";
	    			//|| "".equals(mobile.getText().toString()) || "".equals(email.getText().toString()
	    			if ("".equals(cnName.getText().toString()) ||  "".equals(idType.getText().toString()) || "".equals(idNumber.getText().toString())){
//	    				Toast.makeText(PersonPassengerAdd.this, "请填写完整信息", Toast.LENGTH_LONG).show();
	    				BaseHelper.showDialog(PersonPassengerAdd.this, "提示", "请填写完整信息",
	    						R.drawable.infoicon);
	    				return;
	    			}
	    			String name = cnName.getText().toString();
	    			if(!name.matches("(^[\u4e00-\u9fa5]{2,6}$)|(^[a-zA-z][a-zA-z\\s]{0,18}[a-zA-z]$)")){
	    				toast = Toast.makeText(PersonPassengerAdd.this, "姓名应为2-6个中文字符或2-20个英文", Toast.LENGTH_LONG);
	    				toast.setGravity(Gravity.CENTER, 0, 0);
	    				toast.show();
	    				return;				
	    			}
					if ("身份证".equals(idType.getText().toString()) 
							&& !CheckCetiType.isIdCard(idNumber.getText().toString())) {
						toast = Toast.makeText(PersonPassengerAdd.this, "身份证填写不正确", Toast.LENGTH_LONG);
	    				toast.setGravity(Gravity.CENTER, 0, 0);
	    				toast.show();
						return;
					}
					if(!"".equals(mobile.getText().toString())){
						if (!mobile.getText().toString().matches("[0-9]{11}")) {
							toast = Toast.makeText(PersonPassengerAdd.this, "手机号填写不正确", Toast.LENGTH_LONG);
		    				toast.setGravity(Gravity.CENTER, 0, 0);
		    				toast.show();
							return;
						}
					}
					if(!"".equals(email.getText().toString())){
						if (!email.getText().toString().matches("\\w+@(\\w+\\.)+[a-z]{2,3}")) {
							toast = Toast.makeText(PersonPassengerAdd.this, "Email填写不正确", Toast.LENGTH_LONG);
		    				toast.setGravity(Gravity.CENTER, 0, 0);
		    				toast.show();
							return;
						}
					}
					
					if("身份证".equals(idType.getText().toString())){
						birthdayValue = CheckCetiType.getCertiCodeToBirtday(idNumber.getText().toString());
					} else {
						birthdayValue =  birthday.getText().toString();
					}
					System.out.println("birthdayValue="+birthdayValue);
					
	    			HashMap<String, String> map = new HashMap<String, String>();
	    			map.put("passengerName", cnName.getText().toString());
	    			map.put("passengerIdNumber", idType.getText().toString() + " " + idNumber.getText());
	    			map.put("passengerIDType", String.valueOf(FlyUtil.getCardPosition(idType.getText().toString())));
	    			map.put("passengerIDNo", idNumber.getText().toString());
	    			map.put("passagerBirthday", birthdayValue);
	    			map.put("passengerMobile", mobile.getText().toString());
	    			map.put("email", email.getText().toString());
	    			map.put("sex", sex);
	    			Log.i("add passengerIDType ====  ", String.valueOf(FlyUtil.getCardPosition(idType.getText().toString())));
	    			for (int i = 0; i < data.size(); i++) {
	    				Map m = data.get(i);
	    				if (map.get("passengerIDNo").equals(m.get("passengerIDNo"))) {
	    					toast = Toast.makeText(PersonPassengerAdd.this, "已添加该乘客信息", Toast.LENGTH_LONG);
		    				toast.setGravity(Gravity.CENTER, 0, 0);
		    				toast.show();
	    					return;
	    				}
	    			}
	    			
	    			data.add(map);
	    			//保存登机人入数据库中
	    			Passenger passengerNew = new Passenger();
	    			passengerNew.setPassengerName(cnName.getText().toString());
	    			Log.i("PersonPassengerAdd idType", idType.getText().toString());
	    			passengerNew.setPassengerIDType(String.valueOf(FlyUtil.getCardPosition(idType.getText().toString())));
	    			Log.i("PersonPassengerAdd passengerIDType", passengerNew.getPassengerIDType() );
	    			passengerNew.setPassengerIDNo(idNumber.getText().toString());
	    			passengerNew.setPassagerBirthday(birthdayValue);
	    			passengerNew.setPassengerMobile(mobile.getText().toString());
	    			passengerNew.setEmail(email.getText().toString());
	    			passengerNew.setSex(sex);
	    			FavoriteInfoDB.setPassenger(PersonPassengerAdd.this, passengerNew);
	    			
	    			Intent intentA = new Intent();
	    			intentA.setClass(PersonPassengerAdd.this, PersonPassengerList.class);
	    			startActivity(intentA);
	    			break;
    		}
    	}
	};
	
	public void onItemClick(AdapterView<?> arg0, View v, int position,
			long arg3) {
		switch (arg0.getId()) {
			case R.id.mileagerInfo_list:
				this.position = position;
				showDialog(DELETE_MILEAGER_DIALOG);
				break;
		}	
	}
	
	private Dialog buildDeleteDialog() {
		 return new AlertDialog.Builder(this)
         .setTitle("请选择")
         .setItems(R.array.dialog_passenger_list, new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int which) {
                 if(which==0){
                	Intent intenthistory = new Intent(PersonPassengerAdd.this,MileagerInfoEdit.class);
                  	intenthistory.putExtra("position", position);
                  	MileagerInfoEdit.data = mileagerInfoList;
                  	MileagerInfoEdit.fromAction = "ADD";
     				startActivity(intenthistory);
                 }else if(which==1){
                	 mileagerInfoList.remove(position);
             		if(mileagerInfoList.size() != 0) {
             			no_mileagerInfo_alert.setVisibility(View.GONE);
            			Utils.setListViewHeightBasedOnChildren(lv);
                    	sa.notifyDataSetChanged();
            		} else {
            			no_mileagerInfo_alert.setVisibility(View.VISIBLE);
            			lv.setVisibility(View.GONE);
            			no_mileagerInfo_alert.setText("暂未添加常旅客！");
            		}
                 }
             }
         })
         .create();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case DELETE_MILEAGER_DIALOG:
				return buildDeleteDialog();
		    case DIALOG_IDTYPE_LIST:
	            return new AlertDialog.Builder(PersonPassengerAdd.this)
	                .setIcon(R.drawable.ic_menu_more)
	                .setTitle("请选择")
	                .setSingleChoiceItems(R.array.paperTypes, 0, new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    	String[] arrs = getResources().getStringArray(R.array.paperTypes);
	                    	idType.setText(arrs[whichButton]);
	                    	if(!arrs[whichButton].equals("身份证")){
	                    		birthdayLay.setVisibility(View.VISIBLE);
	                    	} else {
	                    		birthdayLay.setVisibility(View.GONE);
	                    	}
	                    	dialog.dismiss();
	                        /* User clicked on a radio button do some stuff */
	                    }
	                })
	                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    
	                    }
	                })
	                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    }
	                })
	               .create();
		    case DATE_DIALOG_ID:
		    	return new DatePickerDialog(this, dsl, mYear, mMonth, mDay);
		    default:
				return null;
		}
	}
	
    //准备日期设置监听器
    private OnDateSetListener dsl = new DatePickerDialog.OnDateSetListener(){

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear =year;
			mMonth= monthOfYear;
			mDay= dayOfMonth;
			birthday.setText(mYear+"-"+(mMonth+1)+"-"+mDay);
		}
    };

	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	}  
	
}
